package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;


public class SecurityConfigUserService implements UserDetailsService {

    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.findUserByUsername(username);
        if (sysUser == null) {
            return null;
        }

        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
//        遍历用户角色
        for (Role role : sysUser.getRoles()) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role.getKeyword());
            grantedAuthorityList.add(simpleGrantedAuthority);
//       遍历每个角色对应的权限
            for (Permission permission : role.getPermissions()) {
                SimpleGrantedAuthority simpleGrantedAuthority1 = new SimpleGrantedAuthority(permission.getKeyword());
                grantedAuthorityList.add(simpleGrantedAuthority1);
            }
        }
//        参数3:用户相应的权限集合对象
        User user = new User(sysUser.getUsername(), sysUser.getPassword(), grantedAuthorityList);

        return user;
    }
}
